class QuestionsController < ApplicationController
  before_filter :authenticate_user!
  before_filter do
    @competition_tab = 'question_lists'
  end
  
  # GET /questions
  # GET /questions.json
  def index
    @questions = Question.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @questions }
    end
  end

  # GET /questions/1
  # GET /questions/1.json
  def show
    @question = Question.find(params[:id])
    @competition = @question.question_list.competition

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @question }
    end
  end

  # GET /questions/new
  # GET /questions/new.json
  def new
    @question = Question.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @question }
    end
  end

  # GET /questions/1/edit
  def edit
    @question = Question.find(params[:id])
  end

  # POST /questions
  # POST /questions.json
  # POST /questions.js
  def create
    @question = Question.new(params[:question])
    @really_submit = params[:really_submit] != ''
    @question_version = QuestionVersion.create_from_params(params[:question_version], 
        false)
    @question_version.author = current_user
    @question_version.question = @question

    if @really_submit
      @question_version.save
      puts "#{@question_version.errors.any?}"
      if !@question_version.errors.any?
        @question.save
      end
    end
    
    respond_to do |format|
      format.js
    end
  end

  # PUT /questions/1
  # PUT /questions/1.json
  # PUT /questions/1.js
  def update
    @question = Question.find(params[:id])
    @really_submit = params[:really_submit] != ''
    @question.current_version.update_from_params(params[:question_version], @really_submit)
    # if @really_submit
    #   @question.update_attributes(params[:question])
    # end

    respond_to do |format|
      format.js
    end
  end

  # DELETE /questions/1
  # DELETE /questions/1.json
  def destroy
    @question = Question.find(params[:id])
    @question_list = @question.question_list
    if @question_list.published
      @question.removed_by = current_user.id
      @question.removed_at = Time.now
      @question.save
    else
      @question.destroy
    end

    respond_to do |format|
      format.html { redirect_to question_list_url(@question_list) }
      #format.json { head :no_content }
    end
  end

  # POST /questions/1/vote.js
  def vote
    @question = Question.find(params[:id])
    if @question.question_list.vote && params[:value]
      @question.current_version.vote.vote(current_user, params[:value].to_i)
    end
    respond_to do |format|
      format.js
    end
  end
end
